#include <iostream>
#include <memory>
#include <cctype>
#include <algorithm>
#include "Comm.hpp"
#include "Tcpserver.hpp"
#include "Translate.hpp"

using namespace std;

void Usage(std::string proc) // 提示说明
{
    cout << "Usage: \n\t" << proc << " local_port\n"
         << endl;
}

Translate trans;

void Interact(int sockfd, string& out, const string& in)
{
    char buffer[1024];
    ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
    if (n > 0)
    {
        buffer[n] = 0;
        
        write(sockfd, in.c_str(), in.size());
    }
    else if (n == 0) // 读到了文件结尾（表示对端关闭了连接）
    {
        lg.LogMessage(Info, "client quit...\n");
    }
    else
    {
        lg.LogMessage(Error, "read socket error, errno code: %d,error string: %s\n", errno, strerror(errno));
    }
}

// 可以定期向服务器发送最小服务请求，如果得到了回复，说明服务器是正常的
// 这个机制，称之为心跳机制
void Ping(int sockfd, InetAddr addr)
{
    string message;
    Interact(sockfd, message, "Pong");
}
void Translate(int sockfd, InetAddr addr)
{
    char wordbuf[128];
    int n = read(sockfd, wordbuf, sizeof(wordbuf)-1);
    if(n > 0)   wordbuf[n] = 0;
    string chinese = trans.Excute(wordbuf);
    write(sockfd, chinese.c_str(), chinese.size());
    lg.LogMessage(Debug, "%s Translate service, %s->%s\n", addr.PrintDebug().c_str(), wordbuf, chinese.c_str());
}

//改为大写
void Transform(int sockfd, InetAddr addr)
{
    char message[128];
    int n = read(sockfd, message, sizeof(message)-1);
    if(n > 0) message[n] = 0;
    string messagebuf = message;
    transform(messagebuf.begin(), messagebuf.end(), messagebuf.begin(),[](unsigned char c){
        return std::toupper(c);
    });
    write(sockfd, messagebuf.c_str(),messagebuf.size());

}
void DefaultService(int sockfd, InetAddr addr)
{
    cout << "default" << endl;
}
// ./tcp_server 8888
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return Usage_Err;
    }
    uint16_t port = stoi(argv[1]);
    unique_ptr<TcpServer> tsvr = make_unique<TcpServer>(port);

    tsvr->RegisterFunc("ping", Ping);
    tsvr->RegisterFunc("translate", Translate);
    tsvr->RegisterFunc("transform", Transform);
    tsvr->RegisterFunc("default", DefaultService);
    tsvr->Init();
    tsvr->Start();

    return 0;
}